<script>
import { findAll, add } from "@/api/deptchange.js";
import { findAlldept } as deptAPI from "@/api/dept.js";

export default {
  data() {
    return {
      formLabelWidth: "120px",
      dialogFormVisible: false,
      deptchange: {},
      tableData: [],
      deptList: [],
    };
  },
  async mounted() {
    await this.fetchData();
    await this.loadDeptOptions();
  },
  methods: {
    async fetchData() {
      try {
        const result = await findAll();
        if (result.data.code === 1) {
          this.tableData = result.data.data;
        }
      } catch (error) {
        this.handleError(error, 'Failed to fetch department changes');
      }
    },
    async loadDeptOptions() {
      try {
        const result = await deptAPI.findAlldept();
        this.deptList = result.data.data;
      } catch (error) {
        this.handleError(error, 'Failed to load departments');
      }
    },
    async deleteById(id) {
      const confirmResult = await this.$confirm("确认删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      });

      if (confirmResult) {
        try {
          const result = await deleteById(id);
          if (result.data.code === 1) {
            this.$message.success("恭喜你，删除成功");
            await this.fetchData();
          } else {
            this.$message.error(result.data.msg);
          }
        } catch (error) {
          this.handleError(error, 'Delete failed');
        }
      }
    },
    async add() {
      try {
        let method = this.deptchange.id ? update(this.deptchange) : add(this.deptchange);
        const result = await method;
        if (result.data.code === 1) {
          this.$message.success("恭喜你，保存成功");
          this.dialogFormVisible = false;
          this.deptchange = {};
          await this.fetchData();
        } else {
          this.$message.error(result.data.msg);
        }
      } catch (error) {
        this.handleError(error, 'Save failed');
      }
    },
    handleError(error, message) {
      console.error(error);
      this.$message.error(message);
    },
  },
};
</script>
